<template>
  <div class="app-container-flex">
    <NewFullScreen v-model="showDialog" :title="title">
      <template v-slot:full-button>
        <el-button @click="save()" :disabled="!canSave">保存</el-button>
      </template>
      <div class="model-panel">
        <div v-if="btnCode !== 'depotReturn'" class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <PageForm
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            v-model:data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-storeDepotName>
              <el-input
                class="not-mongolia"
                type="input"
                :required="true"
                :disabled="true"
                placeholder="请选择仓库"
                v-model="formInfo.data.storeDepotName"
              >
                <template #append>
                  <el-icon @click="selectStoreDepot"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </PageForm>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')"></Tooltip>
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <NewPageFilter
            v-model:query="filterInfo.query"
            :filter-btn="filterInfo.list"
          >
            <template v-slot:filter-addProduct>
              <el-button @click="addProduct()">添加产品</el-button>
            </template>
            <template v-slot:filter-removeProduct>
              <el-button :disabled="!canRemoveProduct" @click="removeProduct"
                >删除产品</el-button
              >
            </template>
          </NewPageFilter>
          <div class="flex_full_item">
            <!-- 表格 -->
            <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
              <PageTable
                v-model:query="filterInfo.query"
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-reasonValue="scope">
                  <el-form-item
                    class="margin-bottom"
                    :prop="`data.${scope.$index}.reason`"
                  >
                    <SelectModel
                      v-model.lazy="scope.row.reason"
                      type-code="purch_return_reason"
                    />
                  </el-form-item>
                </template>
              </PageTable>
            </el-form>
          </div>
          <NewSelectProductToSmartCabinet
            v-if="productInfo.visible"
            v-model:showDialog="productInfo.visible"
            v-model:query="productInfo.query.queryMap"
            :api="productInfo.api"
            :query-params="productInfo.query.queryParams"
            :tableKey="productInfo.tableKey"
            :allowCoverFilterParams="true"
            @callback="selectProduct"
          />
          <!-- 仓库 -->
          <SelectDepot
            v-if="selectStoreDepotInfo.visible"
            v-model:showDialog="selectStoreDepotInfo.visible"
            :checkBox="false"
            :query="selectStoreDepotInfo.query"
            :highlightRow="true"
            :checkLock="true"
            :saveEmpty="true"
            @callback="selectStoreDepotCallBack"
          />
        </div>
      </div>
    </NewFullScreen>
  </div>
</template>

<script setup name="batchData">
import {
  getSmartCabinetPendOutRecordCustomizeListPage,
  saveSmartCabinetPendOutRecordConsumeConfirm,
  saveSmartCabinetPendOutRecordTransferDepot,
  saveSmartCabinetPendOutRecordPurchReturn,
  saveSmartCabinetPendOutRecordScrapExport,
  saveSmartCabinetPendOutRecordReturnDepot,
  saveSmartCabinetPendOutRecordUseReturnExport,
} from '@/api/smartCabinet.js'
import { getCustomizeSetting } from '@/api/customize'
import {
  setDisableTime,
  _getCurrentFiscalPeriod,
} from '@/common/js/dateOperation'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '',
  },
  btnCode: {
    type: String,
    default: '',
  },
  idNot: {
    type: String,
    default: '',
  },
  selectionsData: {
    type: Array,
    default: () => {
      return []
    },
  },
})
const formRefs = ref([])
const formInfo = ref({
  ref: null,
  data: {},
  fieldList: [],
  cloneFieldList: [
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      clearable: false,
    },
    { label: '备注', value: 'remark', type: 'input' },
  ],
  rules: {
    businessDate: [
      { required: true, message: '请选择业务日期', trigger: 'change' },
    ],
    storeDepotName: [
      { required: true, message: '请选择仓库', trigger: 'change' },
    ],
    returnType: [
      { required: true, message: '请选择采购退货类型', trigger: 'change' },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {},
  },
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [...props.selectionsData],
  selections: [],
  fieldList: [],
  tableKey: '',
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: removeProduct,
        show: true,
      },
    ],
  },
})
//选择产品相关
const productInfo = ref({
  api: getSmartCabinetPendOutRecordCustomizeListPage,
  visible: false,
  tableKey:
    'smartCabinetPendOutRecordAddInfo-com.slip.spd.entity.vo.smartCabinet.SmartCabinetPendOutRecordVO',
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      smartCabinetDepotId: {
        queryType: 'IN',
        value: null,
      },
      supplierId: {
        queryType: 'IN',
        value: null,
      },
      status: {
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      processStatus: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
      // depotAuth: {
      //   asTbName: 'smart_cabinet_list',
      //   columnName: 'depot_id',
      //   queryType: 'IN',
      //   queryCategory: 'AND',
      //   value: 'depotAuth',
      // },
      // deptAuth: {
      //   asTbName: 'smart_cabinet_list',
      //   columnName: 'dept_id',
      //   queryType: 'IN',
      //   queryCategory: 'AND',
      //   value: 'deptAuth',
      // },
    },
    queryParams: {},
  },
})
const selectStoreDepotInfo = ref({
  visible: false,
  query: {
    // depotAuth: 'id',
    useTypeId: '1',
    status: 1,
    subDepotId: props.btnCode == 'collectReturn' ? props.idNot : '',
    idNot: props.idNot,
    // isCargoSpaceManage: 0,
  },
})
const saveApi = ref('')

const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    emits('update:visible', val) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.data.length
})
onMounted(() => {
  let obj = {}
  if (props.btnCode == 'purchaseReturn') {
    obj = {
      reasonValue: {
        label: '退货原因',
        value: 'reasonValue',
        asValue: 'reason',
        type: 'slot',
        show: false,
        hidden: true,
      },
    }
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  })
  setInfoAndList(props.btnCode)
  getCustomize()
  setBusinessDate()
})

let disStartDate = ref('')
let disEndDate = ref('')
async function setBusinessDate() {
  formInfo.value.data.businessDate = await _getCurrentFiscalPeriod(
    formInfo.value.fieldList,
    proxy,
    disStartDate,
    disEndDate
  )
}
function setInfoAndList(code) {
  let arr = []
  const defaultInfo = props.selectionsData[0]
  let tempKey
  if (code === 'confirmConsumption') {
    // 确认消耗
    tempKey =
      'smartCabinetPendOutRecordConsume-com.slip.spd.entity.vo.stock.ConsumeOrderDetailVO'
    saveApi.value = saveSmartCabinetPendOutRecordConsumeConfirm
  } else if (code === 'stockTransfer') {
    // 移库
    arr = [
      {
        label: '出库仓库',
        value: 'exportDepotName',
        type: 'input',
        disabled: true,
      },
      {
        label: '出库部门',
        value: 'exportDeptName',
        type: 'input',
        disabled: true,
      },
      { label: '入库仓库', value: 'storeDepotName', type: 'slot' },
      {
        label: '入库部门',
        value: 'storeDeptName',
        type: 'input',
        disabled: true,
      },
    ]
    const keyObj = {
      exportDepotName: 'smartCabinetDepotName',
      exportDepotId: 'smartCabinetDepotId',
      exportDeptName: 'smartCabinetDeptName',
      exportDeptId: 'smartCabinetDeptId',
    }
    setFormInfo(keyObj, defaultInfo)
    tempKey =
      'smartCabinetPendOutRecordTransfer-com.slip.spd.entity.vo.stock.TransferOrderDetailVO'
    saveApi.value = saveSmartCabinetPendOutRecordTransferDepot
  } else if (code === 'purchaseReturn') {
    // 采购退货
    arr = [
      {
        label: '退货仓库',
        value: 'depotName',
        type: 'input',
        disabled: true,
      },
      {
        label: '退货部门',
        value: 'deptName',
        type: 'input',
        disabled: true,
      },
      {
        label: '采购退货类型',
        value: 'returnType',
        type: 'select-model',
        code: 'purch_return_type',
        required: true,
      },
      {
        label: '退货供应商',
        value: 'supplierName',
        type: 'input',
        disabled: true,
      },
      { label: '供应商联系人', value: 'contact', type: 'input' },
      { label: '供应商联系电话', value: 'phone', type: 'input' },
    ]
    const keyObj = {
      depotName: 'smartCabinetDepotName',
      depotId: 'smartCabinetDepotId',
      deptName: 'smartCabinetDeptName',
      deptId: 'smartCabinetDeptId',
      supplierName: 'supplierName',
      supplierId: 'supplierId',
    }
    setFormInfo(keyObj, defaultInfo)
    tempKey =
      'smartCabinetPendOutRecordPurchReturn-com.slip.spd.entity.vo.purch.PurchReturnDetailVO'
    saveApi.value = saveSmartCabinetPendOutRecordPurchReturn
  } else if (code === 'collectReturn') {
    // 领用退回
    arr = [
      {
        label: '退回人',
        value: 'applicationUserName',
        type: 'input',
        disabled: true,
      },
      {
        label: '退出仓库',
        value: 'exportDepotName',
        type: 'input',
        disabled: true,
      },
      {
        label: '退出部门',
        value: 'exportDeptName',
        type: 'input',
        disabled: true,
      },
      { label: '退入仓库', value: 'storeDepotName', type: 'slot' },
      {
        label: '退入部门',
        value: 'storeDeptName',
        type: 'input',
        disabled: true,
      },
    ]
    const keyObj = {
      applicationUserName: 'accessUserName',
      applicationUserId: 'accessUserId',
      exportDepotName: 'smartCabinetDepotName',
      exportDepotId: 'smartCabinetDepotId',
      exportDeptName: 'smartCabinetDeptName',
      exportDeptId: 'smartCabinetDeptId',
    }
    setFormInfo(keyObj, defaultInfo)
    tempKey =
      'smartCabinetPendOutRecordUseReturn-com.slip.spd.entity.vo.use.UseReturnExportOrderDetailVO'
    saveApi.value = saveSmartCabinetPendOutRecordUseReturnExport
  } else if (code === 'scrap') {
    // 报废
    arr = [
      {
        label: '出库仓库',
        value: 'depotName',
        type: 'input',
        disabled: true,
      },
      {
        label: '出库部门',
        value: 'deptName',
        type: 'input',
        disabled: true,
      },
    ]
    const keyObj = {
      depotName: 'smartCabinetDepotName',
      depotId: 'smartCabinetDepotId',
      deptName: 'smartCabinetDeptName',
      deptId: 'smartCabinetDeptId',
    }
    setFormInfo(keyObj, defaultInfo)
    tempKey =
      'smartCabinetPendOutRecordScrap-com.slip.spd.entity.vo.stock.ScrapExportOrderDetailVO'
    saveApi.value = saveSmartCabinetPendOutRecordScrapExport
  }
  formInfo.value.fieldList = arr.concat(
    proxy.$fn.deepClone(formInfo.value.cloneFieldList)
  )
  setDisableTime(formInfo.value.fieldList, disStartDate, disEndDate)
  if (code === 'depotReturn') {
    // 退回本仓库
    formInfo.value.fieldList = []
    tempKey =
      'smartCabinetPendOutRecord-com.slip.spd.entity.vo.smartCabinet.SmartCabinetPendOutRecordVO'
    saveApi.value = saveSmartCabinetPendOutRecordReturnDepot
  }
  tableInfo.value.tableKey = tempKey
}
function getCustomize() {
  let param = {
    tableKey: tableInfo.value.tableKey,
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      filterInfo.value.query.customizeUserVO = data
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function addProduct() {
  productInfo.value.query.queryMap.id.value = null
  const arr1 = ['stockTransfer', 'scrap', 'collectReturn']
  if (arr1.indexOf(props.btnCode) !== -1) {
    productInfo.value.query.queryMap.smartCabinetDepotId.value =
      props.selectionsData[0].smartCabinetDepotId
  } else if (props.btnCode === 'purchaseReturn') {
    productInfo.value.query.queryMap.smartCabinetDepotId.value =
      props.selectionsData[0].smartCabinetDepotId
    productInfo.value.query.queryMap.supplierId.value =
      props.selectionsData[0].supplierId
  }
  if (tableInfo.value.data.length) {
    productInfo.value.query.queryMap.id.value = tableInfo.value.data
      .map((item) => item.id)
      .toString()
  }
  productInfo.value.visible = true
}
//删除产品
function removeProduct(selectRow = undefined) {
  if (selectRow && selectRow.productId) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
//选择产品
function selectProduct(rows) {
  if (rows && rows.length) {
    tableInfo.value.data = rows.concat(tableInfo.value.data)
  }
}
//选择仓库
function selectStoreDepot() {
  selectStoreDepotInfo.value.visible = true
}
function selectStoreDepotCallBack(data = undefined) {
  const keyObj = {
    storeDepotName: 'name',
    storeDepotId: 'id',
    storeDeptName: 'deptName',
    storeDeptId: 'deptId',
  }
  if (data && data.id) {
    setFormInfo(keyObj, data)
  } else {
    setFormInfo(keyObj, {})
  }
}
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const details = tableInfo.value.data
    const data = formInfo.value.data
    if (!details.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '请添加有效的产品',
      })
      return
    }
    data.mergeDetails = details
    // 退回本仓库 只需要传一个数组就行
    let result = props.btnCode == 'depotReturn' ? details : data
    saveApi.value(result).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emits('returnBack', false)
      }
    })
  })
}
// 根据定义值赋值给formInfo默认值
function setFormInfo(obj, info) {
  for (let k in obj) {
    formInfo.value.data[k] = info[obj[k]]
  }
}
</script>

<style scoped lang="scss"></style>
